//app.js
// wxa8af6e94d82b192f
App({
  param: {
    scanCallCoupon: {}
  },
  tips: {
    noPageData: "没有更多数据了",
    error: "服务器异常,请稍后再试"
  },
  url: {
    baseUrl:"https://apis.app.ltaste.cn/wechat"   //客户地址
    // baseUrl: "https://apis.loveke.xin/wechat" //公司地址
    // baseUrl: "http://localhost/wechat"
  },
  keys: {
    USER_INFO: "USER_INFO",
    INTERFACE_TOKEN: "INTERFACE_TOKEN",
    IS_RELOGIN: false
  },
  onLaunch: function () {
    this.checkSession(null);
  },
  /**
   * 检测session是否有效
   */
  checkSession(cb) {
    var that = this
    wx.checkSession({
      success: function () {
        console.log('session 有效')
      },
      fail: function () {
        console.log("session 失效")
        //登录态过期 重新登录 
        that.userLogin()
      }
    });
  },
  /**
   * ajax请求
   * url:请求地址
   * data:json数据
   * s:成功回调如无需要可填null
   * f:失败回调,如无需要可填null
   * h:头部信息,如果无特殊要求可填null
   */
  ajax: function (url, data, s, f, h) {
    var that = this
    // console.log("访问地址:" + url)
    // console.log("携带数据为start:")
    // console.log(data)
    // console.log("携带数据为end:")
    var data = data == null ? {} : data;
    var h = h == null ? {} : h
    if (h["Content-Type"] == null) {
      h["Content-Type"] = "application/json"
    }
    var authorization = this.getStorage(this.keys.INTERFACE_TOKEN)
    if (authorization == null || authorization == "") {
      that.userLogin()
      that.keys.IS_RELOGIN = true
      setTimeout(function () {
        that.ajax(url, data, s, f, h)
      }, 3000)
      return
    }
    h["authorization"] = authorization
    wx.request({
      url: url,
      data: data,
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      header: h, // 设置请求的 header
      success: function (res) {
        // console.log("成功返回数据start: 访问地址为:" + url)
        // console.log(res)
        var statusCode = res.statusCode
        if (statusCode == 401) {
          console.log("token失效,正在重新登陆")
          that.userLogin()
          that.keys.IS_RELOGIN = true
          setTimeout(function () {
            that.ajax(url, data, s, f, h)
          }, 3000)
          return
        }
        if (s != null)
          s(res);
        // console.log("成功返回数据end:")
      },
      fail: function (res) {
        if (f != null)
          f(res);
      },
      complete: function (res) {

      }
    })
  },
  //用户登陆
  userLogin: function () {
    console.log("进入了登陆方法")
    if (this.keys.IS_RELOGIN)
      return
    var that = this
    wx.login({
      success: function (res) {
        console.log("获取用户登陆code")
        if (res.code) {
          var data = { code: res.code };
          wx.request({
            url: that.url.baseUrl + "/login",
            method: 'POST',
            data: data,
            header: { "Content-Type": "application/x-www-form-urlencoded" },
            success: function (res) {
              console.log("code发送调用成功");
              that.keys.IS_RELOGIN = false
              that.setStorage(that.keys.INTERFACE_TOKEN, res.data.token);
              console.log(that.getStorage(that.keys.INTERFACE_TOKEN));
              //获取用户信息
              wx.getUserInfo({
                success: function (res) {
                  console.log("调用用户信息成功");
                  var userInfo = res.userInfo
                  var nickName = userInfo.nickName
                  var avatarUrl = userInfo.avatarUrl
                  var gender = userInfo.gender //性别 0：未知、1：男、2：女
                  userInfo = { sex: gender, head_icon: avatarUrl, real_name: nickName, aaaa: 111111 };
                  //console.log(res);
                  //更新用户 
                  that.ajax(that.url.baseUrl + "/authUpUser", userInfo, function (res) {
                    that.setStorage(that.keys.USER_INFO, res.data);
                  });
                }, fail: function (res) {
                  that.ajax(that.url.baseUrl + "/authUpUser", null, function (res) {
                    that.setStorage(that.keys.USER_INFO, res.data);
                  });
                  console.log("调用用户信息失败");
                }
              });
            }, fail: function (res) {
              that.keys.IS_RELOGIN = false
              console.log("访问失败")
            }
          })
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }, fail: function (res) {
        console.log("获取用户code失败")
        console.log(res)
      }
    })
  },
  /**
  * 设置key
  */
  setStorage: function (k, v) {
    wx.setStorageSync(k, v);
  },
  /**
   * 移除key
   */
  removeStorage: function (k) {
    wx.removeStorage({ key: k });
  },
  /**
   * 读取key
   */
  getStorage: function (k) {
    return wx.getStorageSync(k);
  },
  getRandomChar(num) {
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    var maxPos = chars.length
    var str = ""
    for (var i = 0; i < num; i++) {
      str += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return str
  },
  //不为空
  notNull:function(obj,defaultobj){
    if(obj==null)
      return defaultobj;
    return obj;
  }
})